package com.s63.modules.login;

import com.s63.modules.security.LoginUser;
import com.s63.modules.token.ITokenService;
import com.s63.modules.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
    @Autowired
    private ITokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;

    public Token login(LoginVO loginVO) {
        // 由spring security自动调用UserDetailsServiceImpl.loadUserByUsername方法
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVO.getUsername(), loginVO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return tokenService.createToken(loginUser);
    }
}
